package org.mspring.mlog.web.module.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.lucene.search.Query;
import org.mspring.mlog.entity.News;
import org.mspring.mlog.service.search.NewsSearchService;
import org.mspring.mlog.service.search.PostSearchService;
import org.mspring.platform.persistence.support.Page;
import org.mspring.platform.utils.RequestUtils;
import org.mspring.platform.utils.StringUtils;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 
 * @author Gao Youbo
 * @since 2013年7月5日
 */
@Widget
@RequestMapping("/search")
public class Web_SearchWidget extends Web_AbstractWidget {

    @Autowired
    private PostSearchService postSearchService;
    @Autowired
    private NewsSearchService newsSearchService;

    @RequestMapping({ "/", "" })
    public String search(@ModelAttribute Page<News> newsPage, HttpServletRequest request, HttpServletResponse response, Model model) {
        String word = RequestUtils.getRequestParameterAsString(request, "w");
        if (StringUtils.isNotBlank(word)) {
            word = StringUtils.encoding(word, "ISO-8859-1", "UTF-8").trim();
            String[] fields = new String[] { "title", "summary", "content" };
            Query query = newsSearchService.getQueryBuilder().keyword().onFields(fields).matching(word).createQuery();
            newsPage = newsSearchService.searchPage(newsPage, query, News.class);
        }
        model.addAttribute("newsPage", newsPage);
        model.addAttribute("w", word);
        return "skin:/search";
    }
}
